from django import forms

__author__ = 'Sea'

def query_decorator(default_index = 0, default_scope = 30):
    def decorator(view_func):
        def _wrapper_view_func(request, *args, **kwargs):
            form = QueryForm(request.REQUEST)
            index = default_index
            scope = default_scope
            if form.is_bound and form.is_valid():
                data = form.cleaned_data
                index = data.get('index')
                scope = data.get('scope')
            request.query_params = QueryParam(index, scope)
            return view_func(request, *args, **kwargs)
        return _wrapper_view_func
    return decorator

class QueryParam(object):
    def __init__(self, index, scope):
        self.index = index
        self.scope = scope

class QueryForm(forms.Form):
    index = forms.IntegerField(min_value = 0, initial = 0, required = False)
    scope = forms.IntegerField(min_value = 1, initial = 5, required = False)

    def clean_index(self):
        index = self.cleaned_data.get('index')
        if not index:
            index = 0
        return index

    def clean_scope(self):
        scope = self.cleaned_data.get('scope')
        if not scope:
            scope = 5
        return scope